#include "lvgl/lvgl.h"
#include "stdio.h"
#include <fcntl.h>
#include <linux/input.h>
static void keypad_init(void);
static void keypad_read(lv_indev_drv_t *indev_drv, lv_indev_data_t *data);
static uint32_t keypad_get_key(void);

lv_indev_t *indev_keypad;

void lv_port_indev_init(void)
{
    static lv_indev_drv_t indev_drv;

    /*Initialize your keypad or keyboard if you have*/
    keypad_init();

    /*Register a keypad input device*/
    lv_indev_drv_init(&indev_drv);
    indev_drv.type = LV_INDEV_TYPE_KEYPAD;
    indev_drv.read_cb = keypad_read;
    indev_keypad = lv_indev_drv_register(&indev_drv);
    printf("lv_port_indev_init succrssful \n");
}

int keypad;
/*Initialize your keypad*/
static void keypad_init(void)
{
    /*Your code comes here*/
    keypad = open("/dev/input/event1", O_RDWR);
    if (keypad != 2)
    {
        printf("keypad initialized successful\n");
    }
    else
    {
        printf("keypad initialized fail!\n");
    }
}

/*Will be called by the library to read the mouse*/
static void keypad_read(lv_indev_drv_t *indev_drv, lv_indev_data_t *data)
{
    static uint32_t last_key = 0;

    sdl_keyboard_read(indev_drv, data);
    /*Get whether the a key is pressed and save the pressed key*/
    uint32_t act_key = 0;
    if (data->state != 0)
    {
        data->state = LV_INDEV_STATE_PR;
        /*Translate the keys to LVGL control characters according to your key definitions*/
        switch (data->key)
        {
        case 49:
            act_key = LV_KEY_NEXT;
            break;
        case 50:
            act_key = LV_KEY_PREV;
            break;
        case 17:
            act_key = LV_KEY_UP;
            break;
        case 18:
            act_key = LV_KEY_DOWN;
            break;
        case 20:
            act_key = LV_KEY_LEFT;
            break;
        case 19:
            act_key = LV_KEY_RIGHT;
            break;
        case 48:
            act_key = LV_KEY_ENTER;
            break;
        }
        printf("end_diff:%d,state:%d,key:%d\n", act_key, data->state, data->key);
        last_key = act_key;
    }
    else
    {
        data->state = LV_INDEV_STATE_REL;
    }
    data->key = last_key;
}

/*Get the currently being pressed key.  0 if no key is pressed*/
static uint32_t keypad_get_key(void)
{
    /*Your code comes here*/
    struct input_event keypad_info;
    // if (read(keypad, &keypad_info, sizeof(struct input_event)) > 0)
    // {
    //     if (keypad_info.type == EV_KEY)
    //     {
    //         printf("key:%d,state:%d", keypad_info.code, keypad_info.value);
    //         return keypad_info.code;
    //     }
    // }
    return 0;
}